package com.qf.exception;

import com.qf.constant.CommonConstant;
import com.qf.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljw
 * @version 1.0
 * @Date 2024/12/26 11:06
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler(CommonException.class)
    public R commExceptionHandler(CommonException e){
        log.error(e.getMsg());
        e.printStackTrace();
        return R.fail(CommonConstant.ERROR,e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e){
        log.error(e.getMessage());
        e.printStackTrace();
        return R.fail("未知异常请联系管理员！");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler2(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return R.fail(500, message);
    }
}
